#coding:utf-8

import base64
import requests


def getToken(ak, sk):
    # client_id 为官网获取的AK， client_secret 为官网获取的SK
    host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id='+ ak +'&client_secret=' + sk
    response = requests.get(host)
    if response:
         return response.json()


'''
人像动漫化
'''
def selfieAnime(filePath, access_token):
    request_url = "https://aip.baidubce.com/rest/2.0/image-process/v1/selfie_anime"
    # 二进制方式打开图片文件
    f = open(filePath, 'rb')
    img = base64.b64encode(f.read())

    params = {"image":img}
    request_url = request_url + "?access_token=" + access_token
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = requests.post(request_url, data=params, headers=headers)
    #if response:
    #    print(response.json()['log_id'])
    with open('ttt.jpg','wb') as f:
        f.write(base64.b64decode(response.json()['image']))
    


filePath = 'luer.jpg'
client_id = 'rPMez53buIjrBOgW1BgRfLpH'
client_secret = 'R4jfZqnnuMszB8DhLtGKaNXYrnBCDhIp'

token = getToken(client_id, client_secret)
selfie_anime(filePath, token['access_token'])

